package com.itheima.tlias84.aspect;

import com.alibaba.fastjson2.JSONObject;
import com.itheima.tlias84.entity.Emp;
import com.itheima.tlias84.entity.OperateLog;
import com.itheima.tlias84.mapper.EmpMapper;
import com.itheima.tlias84.mapper.OperateLogMapper;
import com.itheima.tlias84.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @Aspect 标识切面类
 */
@Slf4j
@Aspect
@Component
public class LogAspect {
    @Resource
    OperateLogMapper logMapper;
    @Resource
    HttpServletRequest request;
    @Resource
    EmpMapper empMapper;

    @Around("@annotation(com.itheima.tlias84.annotaion.Log)")
    public Object insertLog(ProceedingJoinPoint joinPoint) {
        //执行父类方法
        try {
            long start = System.currentTimeMillis();
            Object proceed = joinPoint.proceed();
            long end = System.currentTimeMillis()-start;
            //获取登录人的id
            String token = request.getHeader("token");
            JSONObject jsonObject = JwtUtils.verifyToken(token);
            Emp emp = empMapper.selectEmpByUsername(jsonObject.getString("username"));
            log.info("操作{}方法插入日志", joinPoint.getSignature().getName());
            OperateLog build = OperateLog.builder().className(joinPoint.getTarget().getClass().getName())
                    .methodName(joinPoint.getSignature().getName())
                    .methodParams(Arrays.toString(joinPoint.getArgs()))
                    .operateTime(LocalDateTime.now())
                    .returnValue(proceed.toString())
                    .costTime(end)
                    .operateEmpId(emp.getId())
                    .build();
            int i = logMapper.insertLog(build);
            log.info("插入日志{}条", i);
            return proceed;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}
